﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Esb.Domain.DomainObjects;
using Esb.Domain.Services;

namespace Esb.ManageUI.Controllers
{
    public class ServiceController : BaseController
    {
        //
        // GET: /Service/

        /// <summary>
        /// 查看现有的一个服务的信息
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int id)
        {
            ViewBag.Add = false;
            ServiceService serviceSvc = new ServiceService();
            ServiceDo result = serviceSvc.GetServiceById(id);
            if (result != null && result.Consumers != null)
            {
                ViewBag.Consumers = string.Join(",", result.Consumers);
            }

            return View(result);
        }

        /// <summary>
        /// 修改或删除现有服务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(ServiceDo service)
        {
            ViewBag.Add = false;
            ServiceService serviceSvc = new ServiceService();
            string msg = "";

            string userName = Session["UserName"].ToString();
            if (Request["SubmitType"] == "update")
            {
                string consumers = Request["Consumers"];
                string[] consumers2 = consumers.Split(',');
                service.Consumers = new List<string>();
                foreach (string consumer in consumers2)
                {
                    //int consumerId;
                    service.Consumers.Add(consumer);
                    //if (int.TryParse(consumer, out consumerId))
                    //{

                    //}
                }
                ViewBag.Consumers = consumers;

                bool success = serviceSvc.UpdateService(service, userName, out msg);
                if (success)
                {
                    ViewBag.Scripts = "<Script>alert('更新服务成功！');</Script>";
                }
                else
                {
                    ViewBag.Scripts = "<Script>alert('更新服务失败！可能原因：" + msg + "');</Script>";
                }
            }
            else if (Request["SubmitType"] == "delete")
            {
                bool success = serviceSvc.DeleteServiceById(service.Id, userName);
                if (success)
                {
                    ViewBag.Scripts = "<Script>alert('删除服务成功！');</Script>";
                }
                else
                {
                    ViewBag.Scripts = "<Script>alert('删除服务失败！可能原因：" + msg + "');</Script>";
                }
            }
            else if (Request["SubmitType"] == "log")
            {
                List<OperationLogDo> logs = serviceSvc.QueryServiceLogs(service.Id);
                ViewBag.Logs = logs;
            }

            return View(service);
        }
    }
}
